<template>
<!--  使用的不是封装好的发送请求的方法，需要添加token给后端验证-->
  <el-upload
    class="upload-demo"
    ref="upload"
    :headers="MyHeader"
    action="http://127.0.0.1:9090/oss/uploadImg"
    with-credentials
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-success="handleSuccess"
    multiple
    :limit="1"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
  </el-upload>
</template>

<script>
import {Message} from 'element-ui'

const token = sessionStorage.getItem('token')
export default {
  name: 'ImgUpload',
  data () {
    return {
      fileList: [],
      url: '',
      MyHeader: {token}
    }
  },
  methods: {
    handleRemove (file, fileList) {
    },
    handlePreview (file) {
      // 此处的 file 是整个文件
      // console.log(file.response)
    },
    handleExceed (files, fileList) {
      Message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess (response) {
      this.url = response
      this.$emit('onUpload', this.url)
      // 父组件触发onUpload监听
      Message.success('上传成功')
    },
    clear () {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped>
/* 去掉up-load自带的input按钮*/
/deep/ input[type=file]{
  display: none;
}
</style>
